package msjcalendar;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Element;

import utility.MD5Checksum;
import utility.XmlHelper;

/**
 * @author sebastian
 * Class for saving, loading from a file
 */
public class CalendarFile {
	/**
	 * the filename.
	 */
	private static final String FILENAME = "calendar.sav";
	/**
	 * filename of the checksum file.
	 */
	private static final String CHECKSUM_FILENAME = "calendar.chk";
	/**
	 * the calendar to save/load.
	 */
	private Calendar calendar;
	
	/**
	 *
	 */
	public CalendarFile() {
		this.setCalendar(new Calendar());
	}

	/**
	 * @return the calendar
	 */
	public Calendar getCalendar() {
		return calendar;
	}

	/**
	 * @param calendar the calendar to set
	 */
	public void setCalendar(final Calendar calendar) {
		this.calendar = calendar;
	}
	
	/**
	 * @throws Exception 
	 */
	public void save() throws Exception {
		XmlHelper.init();
		XmlHelper.getXmlDoc().appendChild(this.calendar.toXml());
		StreamResult result =  new StreamResult(FILENAME);
		TransformerFactory tF = TransformerFactory.newInstance();
		Transformer t = tF.newTransformer();
		DOMSource source = new DOMSource(XmlHelper.getXmlDoc());
		t.transform(source, result);
		utility.MD5Checksum.saveChecksum(FILENAME, CHECKSUM_FILENAME);
	}
	
	/**
	 * @throws Exception Checksum Exception
	 */
	public void load() throws Exception {
		if (!MD5Checksum.verifyChecksum(FILENAME, CHECKSUM_FILENAME)) {
			throw new Exception("Could not succesfully validate Checksum.");
		}
		File xmlFile = new File(FILENAME);
		DocumentBuilderFactory dbF = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbF.newDocumentBuilder();
		utility.XmlHelper.setXmlDoc(dBuilder.parse(xmlFile));
		this.calendar = new Calendar((Element) XmlHelper.getXmlDoc().getElementsByTagName("calendar").item(0));
	}
}
